from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, UpdateModelMixin
from . import models, throttlings, ser
from taotao.utils.response import APIResponse
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from django.conf import settings


# Create your views here.


# 短信发送验证码功能
class SendSmsView(GenericViewSet):
    throttle_classes = [throttlings.SmsThrottling, ]

    @action(methods=['GET'], detail=False)
    def send(self, request, *args, **kwargs):
        '''
        发送验证码
        :return:
        '''
        import re
        from taotao.libs.tx_sms import get_code, send_message
        from django.core.cache import cache
        telephone = request.query_params.get('telephone')
        print(telephone)
        if not telephone:
            return APIResponse(code=0, msg='请输入手机号码')
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(code=0, msg='手机号码不合法')
        # 获取验证码
        code = get_code()
        result = send_message(telephone, code)
        if result:
            # 验证码保存，保存在缓存中
            # 验证码key为 sms_cache_%s:即 sms_cache_手机号
            cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)  # 缓存时间：180s
            return APIResponse(code=1, msg='验证码发送成功')
        else:
            return APIResponse(code=0, msg='验证码发送失败')


# 手机注册功能
class RegisterView(CreateModelMixin, GenericViewSet):
    queryset = models.User.objects.all()
    serializer_class = ser.RegisterSerializer

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        username = response.data.get('username')
        return APIResponse(code=1, msg='注册成功', username=username)


# 登录功能
class LoginView(GenericViewSet):
    # 密码登录方式
    @action(methods=['post'], detail=False)
    def login(self, request, *args, **kwargs):
        user_ser = ser.UserSerializer(data=request.data, context={'request': request})
        if user_ser.is_valid():
            token = user_ser.context.get('token')
            username = user_ser.context['user'].username
            avatar = models.User.objects.filter(username=username).values('avatar')[0]
            id = models.User.objects.filter(username=username).values('id')[0].get('id')
            avatar_url = settings.BASE_URL + '/media/' + avatar.get('avatar')
            return APIResponse(token=token, username=username, avatar=avatar_url, id=id)
        else:
            return APIResponse(code=0, msg=user_ser.errors)

    # 验证码登录
    # 1 首先校验手机号
    @action(detail=False)
    def check_telephone(self, request, *args, **kwargs):
        import re
        telephone = request.query_params.get('telephone')
        print(telephone)
        if not re.match(('^1[3-9][0-9]{9}$'), telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            models.User.objects.get(telephone=telephone)
            return APIResponse(code=1)
        except:
            return APIResponse(code=0, msg='手机号不存在')

    # 2 根据验证码登录
    @action(methods=['post'], detail=False)
    def code_login(self, request, *args, **kwargs):
        code_ser = ser.CodeUserSerializer(data=request.data, context={'request': request})
        if code_ser.is_valid():
            token = code_ser.context['token']
            username = code_ser.context['user'].username
            avatar = models.User.objects.filter(username=username).values('avatar')[0]
            id = models.User.objects.filter(username=username).values('id')[0].get('id')
            avatar_url = settings.BASE_URL + '/media/' + avatar.get('avatar')
            return APIResponse(token=token, username=username, avatar=avatar_url, id=id)
        else:
            return APIResponse(code=0, msg=code_ser.errors)


class UserDetailView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def get(self, request, pk):
        from django.conf import settings
        # instance = models.User.objects.filter(id=pk).first()
        serializer = ser.UserInfoSerializer(instance=request.user)
        userinfo =serializer.data
        userinfo['avatar'] = settings.BASE_URL+userinfo['avatar']
        return APIResponse(code=1, result=userinfo)

    def put(self, request, pk):
        user = request.user
        instance = user
        # instance = models.User.objects.filter(id=pk).first() #和request.user一样
        serializer = ser.UserInfoSerializer(instance=instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return APIResponse(code=1, msg='修改成功', result=serializer.data)
        return APIResponse(code=0, msg='修改失败', result=serializer.errors)
